Embedded Python API Reference
This chapter provides information on eCognition's embedded Python API with reference for each class, properties, and methods and gives serveral hints on printing and the usage of external python files in inline scripts. The embedded python API is accessible only from within the rule set algorithm 'python script' and is accessible by importing the eCognition package in python script.
Note - An external eCognition API is provided as python wheel package accessible from python program by installing the ecognitionapi package using the appropriate wheel package. See User Guide > Python Package Documentation .
Exemplary python scripts can be found in User Guide >
How to set up and use an external debugger for python files see User Guide > Python Integration > Debugging python code in eCognition Developer
Following successful first step in Python Integration in eCognition 10.3, we move forward and offer more capabilities that will enable seamless fusion of eCognition rule set and python scripts.
Python Classes, Functions and Methods
To define and call a Python function, the term parameter and argument is used to pass information to the function.
-
class: definition of a specific class of Python object with all of its attributes. Class definition consists of variable assignments or function definitions, resulting in the formation of a new class of object, with its attributes and methods.
-
method: an attribute of a class that is a function. Divided in instance methods (including special methods), class methods, and static methods
-
function: block of code defined with a name that can take arguments and return a value.
To define and call a Python function, parameters and arguments are used to pass information to the function.
-
parameter: variable listed inside parentheses in the function definition.
-
argument: value sent to the function when called on which the function performs action and returns the result.
-
return: results that are returned by the function.
-
raises: Value raised when an operation or function is applied to an object of inappropriate type, e.g. passing arguments with the wrong value. The associated value is a string giving details about the type mismatch, passing arguments with the wrong value.
Input - input_dict
Exemplary Function Argument Structure
{
"scene_info": {
"LLX": float,
"LLY": float,
"resolution": float,
"projection_string": str,
"unit": str
},
"raster": {
"name1": ecognition.Raster,
"name2": ecognition.Raster,
...
},
"vector": {
"name1": ecognition.Vector,
"name2": ecognition.Vector,
...
},
"point_cloud": {
"name1": ecognition.PointCloud,
"name2": ecognition.PointCloud,
...
},
"variable" : {
"name1": str | float,
"name2": str | float,
...
},
"region" : {
"name1": numpy.ndarray (check set_region function for region explanation),
"name2": numpy.ndarray (check set_region function for region explanation),
...
},
"array" : {
"name1": list[str | float],
"name2": list[str | float],
...
}
}
Here “name*” is equal to the name of the selected variable or layer in the 'execute python script' algorithm.
input_dict
This section describes the input for the embedded Python on creation of the 'python script' algorithm. The input parameters are passed to the python script via a data structure called dictionary (name-value pairs). The default name of the dictionary is input_dict and it can contain the following values:
The following chapters explain available methods, parameters, and returns for classes and functions.
Class Raster
Methods
read_data(x=0, y=0, sx=0, sy=0)
Reads data from the raster image object. Can be called multiple times, to allow reading data in chunks for large rasters.
write_data(data, x_offset=0, y_offset=0)
Writes data to the raster image object. Can be called multiple times, to allow writing data in chunks for large rasters.
size()
Returns the size of the raster image.
get_datatype()
Returns the data type of the raster image.
close()
Finalizes raster object. Must be called for new raster objects created with ecognition.Raster.create_raster method.
Static methods
create_raster(name, type)
Static method - Creates an empty raster with the given name and type. If the raster with the specified name already exists, it is deleted, before a new one is created.
create_raster(name, data)
Static method - Creates a raster from the given data, with the given name. Data type is the same as data.dtype. If the raster with the specified name already exists, it is deleted, before a new one is created.
Warning - Note that the Y coordinate for regions was not used correctly in Raster.write_data and in Raster.read_data methods. It was interpreted as top-left corner of the data block, which is different to regions and eCognitions coordinate system, where Y starts at the bottom-left corner. This is fixed since eCognition Version 10.4.0: x/y in Raster.read_data and Raster.write_data methods now interpret Y as bottom coordinate of the data block. Now code like this runs correctly:
region= input_dict["region"]["myRegion"]
data = layer.read_data(int(searchreg[0][0]), int(searchreg[0][1]),
int(searchreg[1][0]), int(searchreg[1][1]))
layer.write_data( data.astype("f"), int(searchreg[0][0]), int(searchreg[0][1]) )
class Raster:
def read_data(self, x: int = 0 , y: int = 0, sx: int = 0, sy: int = 0) -> numpy.ndarray: ...
def write_data(self, data: numpy.ndarray, x_offset: int = 0, y_offset: int = 0) -> None: ...
def size(self) -> Tuple[int, int]: ...
def get_datatype(self) -> numpy.dtype: ...
def close(self) -> None: ...
@overload
@staticmethod
def create_raster(name: str, type: numpy.dtype) -> Raster: ...
@overload
@staticmethod
def create_raster(name: str, data: numpy.ndarray) -> Raster: ...
Class Vector
Methods
get_geometry_type()
Returns the type of the vector geometry.
get_data()
Returns data of the vector as a pandas DataFrame. Geometries are located in the “geometry” column. Other attributes are contained in other columns. Geometries are objects from the shapely.geometry module.
close()
Finalizes the vector object. Must be called for new vector objects created with ecognition.Vector.create_vector method.
Static methods
create_vector(name, geometry_type, data)
Static method - Creates a vector from the given data, with the given name. If the vector with the specified name already exists, it is deleted, before a new one is created. pandas DataFrame given in the data argument must contain a “geometry” column, with at least one geometry. The elements of each DataFrame column must have the same type.
class Vector:
def get_geometry_type(self) -> Literal["Point", "Line", "Polygon", "Point3D", "Line3D", "Polygon3D"]: ...
def get_data(self) -> pandas.DataFrame: ...
def close(self) -> None: ...
@staticmethod
def create_vector(name: str, geometry_type: Literal["Point", "Line", "Polygon", "Point3D", "Line3D", "Polygon3D"],
data: pandas.DataFrame) -> Vector: ...
Class PointCloudChunk
Attributes
x
Read-only property - Returns a numpy array of x coordinate values.
y
Read-only property - Returns a numpy array of y coordinate values.
z
Read-only property - Returns a numpy array of z coordinate values.
intensity
Read-only property - Returns a numpy array of intensity values.
red
Read-only property - Returns a numpy array of red values.
green
Read-only property - Returns a numpy array of green values.
blue
Read-only property - Returns a numpy array of blue values.
classification
Read-only property - Returns a numpy array of classification values.
Special methods
__len__()
Returns the number of points in the chunk.
__repr__()
Returns the string representation of the chunk.
class PointCloudChunk:
@property
def x(self) -> numpy.ndarray: ...
@property
def y(self) -> numpy.ndarray: ...
@property
def z(self) -> numpy.ndarray: ...
@property
def intensity(self) -> numpy.ndarray: ...
@property
def red(self) -> numpy.ndarray: ...
@property
def green(self) -> numpy.ndarray: ...
@property
def blue(self) -> numpy.ndarray: ...
@property
def classification(self) -> numpy.ndarray: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
Class PointCloudChunkIterator
Special methods
__iter__()
Returns self.
__next__()
Returns the next point cloud chunk.
class PointCloudChunkIterator:
def __iter__(self) -> PointCloudChunkIterator: ...
def __next__(self) -> PointCloudChunk: ...
Class PointCloud
Methods
get_chunk_iterator(points_in_chunk=1000000)
Creates a chunk iterator, capable of iterating over the point cloud points. Only one PointCloudChunkIterator may exist at one time.
add_points(x, y, z, intensity, red, green, blue, classification)
Adds point cloud points to the PointCloud object. Each field array must have the same size. Values of the same index correspond to the same point.
get_point_count()
Returns the number of points in the PointCloud.
close()
Finalizes PointCloud object. Must be called for new PointCloud objects created with ecognition.PointCloud.create_point_cloud method.
Static Methods
create_point_cloud(name)
Static method - Creates an empty point cloud, with the given name. If the point cloud with the specified name already exists, it is deleted, before a new one is created.
class PointCloud:
def get_chunk_iterator(self, points_in_chunk: int = 1000000) -> PointCloudChunkIterator: ...
def add_points(self, x: numpy.ndarray, y: numpy.ndarray, z: numpy.ndarray, intensity: numpy.ndarray,
red: numpy.ndarray, green: numpy.ndarray, blue: numpy.ndarray, classification: numpy.ndarray) -> None: ...
def get_point_count(self) -> int: ...
def close(self) -> None: ...
@staticmethod
def create_point_cloud(name: str) -> PointCloud: ...
Class ImageObject
Methods
get_pixel_count()
Returns number of pixels (area) of the image object.
get_classification()
Returns the class name with the best membership.
set_classification(class_name, membership)
Sets classification result to 'membership' for class_name. Any other information is deleted.
get_border_length()
Returns length of the image object border in pixels.
get_inner_pixel()
Returns the pixel which is inside the image object.
get_bounding_box()
Returns the bounding box of the image object.
get_neighbours()
Returns a list of the neighbors of the image object.
get_mask()
Returns the mask of the image object as a matrix of boolean pixel values.
__repr__()
Returns the string representation of the image object.
__str__()
Returns the string representation of the image object.
class ImageObject:
def get_pixel_count(self) -> int: ...
def get_classification(self) -> str: ...
def set_classification(self, classification: str, membership: float) -> None: ...
def get_bounding_box(self) -> tuple[int, int, int, int]: ...
def get_inner_pixel(self) -> tuple[int, int]: ...
def get_mask(self) -> numpy.ndarray: ...
def get_neighbours(self) -> list[ImageObject]: ...
Class ProcessContext
Static Method
get_image_object_iterator()
Creates an image object iterator, capable of iterating over the image objects.
class ProcessContext:
@staticmethod
def get_image_object_iterator() -> ImageObjectIterator: ...
def set_variable(name: str, value: int | float | str) -> None: ...
def set_array(name: str, values: Sequence[int | float | str]) -> None: ...
def set_region(name: str, region: numpy.ndarray) -> None: ...
def wait_for_debugger(host: str = "localhost", port: int = 5678) -> None: ...
def write_message(message: str, show_message_box: bool = False) -> None: ...
Class ImageObjectIterator
Special Methods
__iter__()
Returns self.
__next__()
Returns the next image object
class ImageObjectIterator:
def __iter__(self) -> ImageObjectIterator: ...
def __next__(self) -> ImageObject: ...
Class Feature
Methods
calculate()
Returns feature value for current scene.
calculate(obj: ImageObject)
Returns feature value for the Image Object.
get_min_range_value()
Returns minimum possible feature value.
get_max_range_value()
Returns maximum possible feature value.
Special Methods
__repr__()
Returns the string representation of the feature (unambigious).
__str__()
Returns the string representation of the feature (easier to read).
class Feature:
def _repr_(self) -> str: ...
def _str_(self) -> str: ...
def get_min_range_value() -> float: ...
def get_max_range_value() -> float: ...
Functions
General Functions
set_array(name, values)
Fills an eCognition array with the given values. If an array does not exist, it is created. All elements of the values sequence must have the same type.
set_region(name, region)
Sets an eCognition region. If a region does not exist, it is created. The region array must have a specific shape:
x_pos, y_pos, z_pos, and t_pos are the starting points of a region.
x_size, y_size, z_size, and t_size define the extent of a region.
set_variable(name, value)
Sets an eCognition variable. If it does not exist, it is created.
Utility Functions
wait_for_debugger(host=”localhost”, port=5678)
Blocks code execution and waits for a debugger to connect. Listens on a specified host and port. Debugger is implemented using a debugpy package: https://github.com/microsoft/debugpy, so it is possible to attach to the eCognition process and debug python code using tools that support debugpy.
Please refer to User Guide > Python Integration > Debugging python code in eCognition Developer for details.
write_message(message, show_message_box=False)
Writes a message to the eCognition log file. It also shows up in the View -> Message Console window. If show_message_box is True, then in addition, an information window box shows up with the message. Script execution is blocked until the message box is closed.
Hints
Hint 1 - Printing from python script
Because the console window is disabled in eCognition Developer, Pythons standard output to stdout is not visible. This hint lists some alternatives, in case you need to print some debug information during the development of your script.
The simplest way to print a message from python is to use a ecognition.write_message function:
import ecognition as ecog
def print_message(input_dict):
print_string = "Use write_message function"
ecog.write_message(print_string, True)
Another way to print debug messages would be to use an external log file (a dedicated logging package is recommended for this approach). For example:
def log_to_file(input_dict):
log_file = input_dict["variable"]["var_log_file"]
with open(log_file, "a") as file:
file.write("log entry 1\n")
file.write("log entry 2\n")
Hint 2 - Using external python files in inline script
If you need to import an external file into a python script, the script must be enabled to find that external file. That is done by adding the location of the external file into the process parameter “External script paths”. For example, for the following script: C:\scripts\ExternalFile.py
import ecognition as ecog
def set_variable():
ecog.set_variable("var_from_ext_file", "Set from external file.")
And this inline python script:
from ExternalFile
import set_variable
def use_external_file(input_dict):
set_variable()
It is important to define the parameter “External scripts path” as an array that contains “C:\scripts” as string value.
For more information see also:
Installation Guide > Windows > Python Installation - installation and setup
Reference Book > Algorithms and Processes > Miscellaneous > Python Script - description algorithm and its parameters
Reference Book > Algorithms and Processes > Miscellaneous > Embedded Python API Reference - reference for each class, properties and methods
User Guide > Python Integration - application examples for python scripts and Debugging python code in eCognition Developer